<!-- 数据可视化中心-数据准备-数据源基本信息管理 -->
<template>
    <el-container v-loading.fullscreen.lock="fullscreenLoading" class="custom__container">
        <el-aside width="260px">
            <div class="custom__aside">
                <div class="custom__aside-header">
                    <hsa-title-box title="分类管理"></hsa-title-box>
                    <el-divider class="custom__aside-divider" </el-divider>
                </div>

                <!-- 列表 -->
                <section class="custom__aside-content">
                    <el-tree style="max-width: 600px" v-bind="treeOption" v-on="treeEvents" />
                </section>
            </div>
        </el-aside>

        <el-main class="custom__main">
            <hsa-adaptive-container>
                <!-- 查询 -->
                <hsa-adaptive-pane>
                    <hsa-title-pane>
                        <hsa-title-pane-item title="查询条件">
                            <el-form label-width="100">
                                <hsa-row :gutter="20">
                                    <hsa-col :span="6">
                                        <el-form-item label="数据源名称">
                                            <el-input v-model="queryForm.data.dataPreparationSourceName" />
                                        </el-form-item>
                                    </hsa-col>
                                    <hsa-col :span="6">
                                        <el-form-item label="数据源类型">
                                            <el-select v-model="queryForm.data.dataPreparationSourceType"
                                                placeholder="请选择">
                                                <el-option v-for="item in Typelist" :key="item.value"
                                                    :label="item.label" :value="item.value" />
                                            </el-select>
                                        </el-form-item>
                                    </hsa-col>

                                    <template #footbar>
                                        <el-button type="default" @click="Reset">重 置</el-button>
                                        <el-button type="primary" @click="Search">查 询</el-button>
                                    </template>
                                </hsa-row>
                            </el-form>
                        </hsa-title-pane-item>
                    </hsa-title-pane>
                </hsa-adaptive-pane>

                <!-- 数据源管理 -->
                <hsa-adaptive-pane auto-height>
                    <hsa-title-pane fill>
                        <hsa-title-pane-item title="数据源管理" fill>
                            <template #toolbar>
                                <div></div>
                                <el-button type="primary" @click="Create">新增</el-button>
                                <el-button type="primary" @click="SourceTableConfig">源表配置</el-button>
                            </template>
                            <hsa-table v-bind="tableOption" auto-height></hsa-table>
                        </hsa-title-pane-item>
                    </hsa-title-pane>
                </hsa-adaptive-pane>
            </hsa-adaptive-container>
        </el-main>
    </el-container>

    <!-- 弹出框 -->
    <PopupCreate ref="create" />
    <PopupEditor ref="editor" />
    <PouupTableConfig ref="tableConfig" />
    <PopupRegManage ref="regManage" />
</template>

<script setup lang="ts">
    import { ref, reactive, getCurrentInstance } from 'vue'
    import { Observable, from, map, mergeMap } from 'rxjs';
    import { ElMessage } from 'element-plus'
    import PopupCreate from './popup/create.vue'
    import PopupEditor from './popup/editor.vue'
    import PouupTableConfig from './popup/source-table-config.vue'
    import PopupRegManage from './popup/reg-manage.vue'
    import useCurrentInstance from '@/common/utils/useCurrentInstance'

    // API
    import {
        ApiDataPreparation,
        dataPreparationList,
        type ResponseDataPreparation,
        type ParamDataPreparationList
    } from '~api/DataPreparation'

    // 类型
    import type { HsaTableColumn, HsaTablePaginationProps } from "hsa-ui"

    // 当前实例
    interface Refs {
        create: InstanceType<typeof PopupCreate>
        editor: InstanceType<typeof PopupEditor>
        tableConfig: InstanceType<typeof PouupTableConfig>
        regManage: InstanceType<typeof PopupRegManage>
    }
    const { proxy } = useCurrentInstance<Refs>(getCurrentInstance)

    // 全屏加载
    const fullscreenLoading = ref(false)

    // 目录配置
    const treeOption = reactive({
        data: <{ label: string; rootId: string; children?: ResponseDataPreparation.CatalogueListTeam[] }[]>[
            {
                label: '团队数据源',
                rootId: 'team',
                children: []
            },
            {
                label: '授权给我的',
                rootId: 'personal',
            }
        ],
        props: { label: 'label', children: 'children' },
    })
    const treeEvents = reactive({
        nodeClick(data: { label: string; rootId: string; } & ResponseDataPreparation.CatalogueListTeam) {
            if (data.rootId === 'team') return
            if (data.rootId === 'personal') {
                // 数据源获取
                from(new Promise((r) => { r(fullscreenLoading.value = true) }))
                    .pipe(mergeMap(() => TABLE_AUTH_GIVE_ME()))
                    .subscribe({ complete: () => fullscreenLoading.value = false })
                return
            }

            // 团队数据源获取
            queryForm.data.teamId = data.organizationTeamUserId
            from(new Promise((r) => { r(fullscreenLoading.value = true) }))
                .pipe(mergeMap(() => TABLE_TEAM_LIST()))
                .subscribe({ complete: () => fullscreenLoading.value = false })
        }
    })

    // 新增\修改
    const queryForm = reactive({
        data: Object.assign({}, dataPreparationList()),
        reset: () => queryForm.data = Object.assign({}, dataPreparationList())
    })

    // 驱动类型
    const Typelist = ref<ResponseDataPreparation.DriverTypeOption[]>([])

    // 表格配置
    const tableOption = reactive({
        data: ref<ResponseDataPreparation.DataSourceInfo[]>(),
        columns: ref<HsaTableColumn[]>([
            { align: 'center', label: '数据源名称', width: 220, prop: 'dataPreparationSourceName' },
            { align: 'center', label: '数据源说明', minWidth: 200, prop: 'preparationSourceDesc' },
            { align: 'center', label: '驱动类型', width: 150, prop: 'dataPreparationSourceType' },
            { align: 'center', label: '数据源IP', width: 160, prop: 'ipAddress' },
            { align: 'center', label: '端口', width: 100, prop: 'port' },
            {
                align: 'center',
                label: '操作',
                width: 220,
                fixed: 'right',
                type: 'button',
                buttonGroup: [
                    {
                        type: 'primary',
                        label: '编辑',
                        click: (row) => {
                            proxy.$refs.editor.open(row)
                        }
                    },
                    {
                        type: 'primary',
                        label: '注册管理',
                        click: (row) => {
                            proxy.$refs.regManage.open(row)
                        }
                    },
                    {
                        type: 'primary',
                        label: '删除',
                        click(row) {
                            from(new Promise((r) => { r(fullscreenLoading.value = true) }))
                                .pipe(mergeMap(() => TABLE_DELETE(row.dataPreparationSourceId)))
                                .subscribe({ complete: () => fullscreenLoading.value = false })
                        }
                    }
                ]
            }
        ]),
        paginationUseExternal: true,
        paginationConfig: ref<HsaTablePaginationProps>({
            total: 0,
            pageSize: 10,
            currentPage: 1
        }),
    })

    // 新增
    function Create() {
        proxy.$refs.create.open()
    }

    // 源表配置
    function SourceTableConfig() {
        proxy.$refs.tableConfig.open()
    }

    // 刷新
    function Refresh() {
        if (queryForm.data.teamId) {
            from(new Promise((r) => { r(fullscreenLoading.value = true) }))
                .pipe(mergeMap(() => TABLE_TEAM_LIST()))
                .subscribe({ complete: () => fullscreenLoading.value = false })
            return
        }
        from(new Promise((r) => { r(fullscreenLoading.value = true) }))
            .pipe(mergeMap(() => TABLE_AUTH_GIVE_ME()))
            .subscribe({ complete: () => fullscreenLoading.value = false })
    }

    // 搜索
    function Search() {
        tableOption.paginationConfig.currentPage = 1
        Refresh()
    }

    // 重置
    function Reset() {
        queryForm.reset()
        Search()
    }

    // API:驱动类型
    function DRIVER_TYPE() {
        return new Promise<boolean>((resolve, reject) => {
            from(ApiDataPreparation.driverType())
                .pipe(map((data) => data))
                .subscribe({
                    next(data) {
                        Typelist.value = data
                    },
                    error(error) {
                        console.error(error)
                        reject(error);
                    },
                    complete() {
                        resolve(true)
                    },
                });
        })
    }

    // API:组织团队信息
    function ASIDE_CATALOGUE_LIST() {
        return new Promise<boolean>((resolve, reject) => {
            from(ApiDataPreparation.catalogueList())
                .pipe(map((data) => data))
                .subscribe({
                    next(data) {
                        treeOption.data[0].children = data.map(item => ({
                            ...item,
                            label: item.teamName
                        }))
                    },
                    error(error) {
                        console.error(error)
                        reject(error);
                    },
                    complete() {
                        resolve(true)
                    },
                });
        })
    }

    // API:数据源权限列表
    function TABLE_LIST() {
        if (queryForm.data.teamId) return from(TABLE_TEAM_LIST())
        return from(TABLE_AUTH_GIVE_ME())
    }

    // API:授权给我的:数据源权限列表
    function TABLE_AUTH_GIVE_ME() {
        return new Promise<boolean>((resolve, reject) => {
            const params: ParamDataPreparationList = {
                dataPreparationSourceName: queryForm.data.dataPreparationSourceName,
                dataPreparationSourceType: queryForm.data.dataPreparationSourceType,
                page: tableOption.paginationConfig.currentPage,
                size: tableOption.paginationConfig.pageSize,
            }

            // 请求
            from(ApiDataPreparation.authGiveMe(params))
                .pipe(map((data) => data))
                .subscribe({
                    next(data) {
                        tableOption.data = data.records
                        tableOption.paginationConfig.total = data.total
                    },
                    error(error) {
                        console.error(error)
                        reject(error);
                    },
                    complete() {
                        fullscreenLoading.value = false
                        resolve(true)
                    }
                })
        })
    }

    // API:团队信息:数据源权限列表
    function TABLE_TEAM_LIST() {
        return new Promise<boolean>((resolve, reject) => {
            const params: ParamDataPreparationList = {
                teamId: queryForm.data.teamId,
                dataPreparationSourceName: queryForm.data.dataPreparationSourceName,
                dataPreparationSourceType: queryForm.data.dataPreparationSourceType,
                page: tableOption.paginationConfig.currentPage,
                size: tableOption.paginationConfig.pageSize,
            }

            // 请求
            from(ApiDataPreparation.list(params))
                .pipe(map((data) => data))
                .subscribe({
                    next(data) {
                        tableOption.data = data.records
                        tableOption.paginationConfig.total = data.total
                    },
                    error(error) {
                        console.error(error)
                        reject(error);
                    },
                    complete() {
                        fullscreenLoading.value = false
                        resolve(true)
                    }
                })
        })
    }

    // API:删除数据源
    function TABLE_DELETE(dataPreparationSourceId: string) {
        return new Promise<boolean>((resolve, reject) => {
            if (!dataPreparationSourceId) return resolve(false)

            // 请求
            from(ApiDataPreparation.delete(dataPreparationSourceId))
                .pipe(map((data) => data))
                .pipe(mergeMap((data) => TABLE_LIST().pipe(map(() => data))))
                .subscribe({
                    next() {
                        ElMessage.success({ message: "删除成功", plain: true })
                    },
                    async error(error) {
                        ElMessage.error({ message: '删除失败', plain: true })
                        reject(error)
                    },
                    complete() {
                        resolve(true)
                    }
                })
        })
    }

    // 流程执行
    new Observable((observer) => { observer.next(0); observer.complete() })
        .pipe(mergeMap(() => (async () => fullscreenLoading.value = true)()))
        .pipe(mergeMap(() => DRIVER_TYPE()))
        .pipe(mergeMap(() => ASIDE_CATALOGUE_LIST()))
        // .pipe(mergeMap(() => DRIVER_TYPE()))
        .subscribe({ complete: () => fullscreenLoading.value = false })
</script>

<style lang="scss" scoped>

    // 容器
    .custom__container {
        height: 100%;
        width: 100%;
        position: relative;
    }

    // 左侧
    .custom__aside {
        background: #fff;
        height: 100%;
        width: 100%;

        // 头部
        .custom__aside-header {
            padding: 10px;
            padding-bottom: 0px;
        }


        // 分割线
        .custom__aside-divider {
            margin-bottom: 5px;
        }

        // 内容
        .custom__aside-content {
            box-sizing: border-box;
            padding: 10px;
            padding-top: 5px;
            height: calc(100% - 94px);
            overflow-y: auto;
        }

    }

    // 主要内容
    .custom__main {
        padding: 0;
        padding-left: 10px
    }
</style>
